//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    // banner轮播组件属性
    autoplay: true, // 是否自动切换
    interval: 3000, // 自动切换时间间隔
    navHeight: app.globalData.navHeight,
    navTitleTop: app.globalData.navTitleTop,
    date: ['日', '一', '二', '三', '四', '五', '六'],
    navTitle: '首页',
    monthList: [],
    monthIndex: 0,
    monthCourseList:[],
    courseList:[],
    studentOpt: {},
    isDown: false,
    isCurDate:false,
    // 页面元素
    newsList: []
  },
  onLoad () {
    this.getStudentList() //获取学生列表及选择学生数据
    this.getNewsList() // 获取公告列表
    // 获取日历
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    this.setData({
      year: year,
      month: month,
      isToday: '' + year + month + now.getDate()
    })
  },
  onShow(){
   let studentOpt = wx.getStorageSync('studentOpt');
   if(studentOpt){
     this.getFeedbackTotal(studentOpt.id)
   }
  },
  getNewsList(){
    let flag = false
    app._post_form('/blade-api/contentList', {flag}, (res) => {
      this.setData({
        newsList: res.data
      })
    })
  },
  getHasCourseCalendar(studentId){
    wx.showLoading({
      title: '加载中',
    })
    app._post_form('/blade-api/courseCard', {studentId}, (res) => {
      this.setData({
        monthList: res.data,
        studentId
      })
      if(res.data.length>0){
        let courseDate = res.data[0]||this.data.year+'年'+this.data.month+'月'
        this.getMonthCourseList(studentId, courseDate)
      }else{
        app.alert({
          content:'该学生下暂无课程安排 ，请重新选择学生'
        })
        wx.hideLoading()
        wx.stopPullDownRefresh()
      }

    })
  },
  getMonthCourseList(studentId, courseDate){
    app._post_form('/blade-api/mouth', {studentId, courseDate}, (res) => {
      this.setData({
        monthCourseList: res.data
      })
      let currentMonth= this.data.monthList[this.data.monthIndex]
      let year =currentMonth.substr(0, 4)
      let month =currentMonth.substr(5, 2)
      this.dateInit(year * 1, month* 1-1);
      wx.hideLoading()
    })

  },
  getDayCourseList(studentId, courseDate){
    wx.showLoading({
      title: '加载中',
    })
    app._post_form('/blade-api/cardList', {studentId, courseDate}, (res) => {
      this.setData({
        courseList: res.data
      })
      wx.hideLoading()
    })
  },
  //获取学生反馈总数
  getFeedbackTotal(id){
    app._post_form('/blade-api/num', {id}, (res) => {
      let num=res.data.toString()
      if( res.data>0){
        wx.setTabBarBadge({
          index: 0,
          text:num
        })
      }else{
        wx.removeTabBarBadge({
          index: 0
        })
      }
    })

  },
  // 选择月份
  bindPickerChange(e) {
    let monthIndex = e.detail.value
    let year = this.data.monthList[monthIndex].substr(0, 4)
    let month = this.data.monthList[monthIndex].substr(5, 2)
    this.setData({
      monthIndex,
      year,
      month,
    })
    this.getMonthCourseList(this.data.studentId, this.data.monthList[monthIndex])
    this.dateInit(year * 1, month * 1-1);
  },
  selectHandle() {
    if(this.data.studentList.length>1){
      this.setData({
        isDown: !this.data.isDown
      })
    }
  },
  // 回到顶部
  toTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    this.triggerEvent('scrollEvent', {}) // 可绑定点击标题栏时的事件
  },
  getStudentList(){
    let studentList = wx.getStorageSync('studentList');
    let studentOpt = studentList[0]
    wx.setStorageSync('studentOpt',studentOpt);
    this.setData({studentList, studentOpt}, () => {
      this.getHasCourseCalendar(studentOpt.id) //获取某个学生有课程的日期
      this.getFeedbackTotal(studentOpt.id)// 获取老师反馈总数
    })
  },
  /**
   * 切换学生
   */
  changeStudent(e){
    let index = e.currentTarget.dataset.index
    let studentOpt = this.data.studentList[index]
    wx.setStorageSync('studentOpt',studentOpt);
    this.setData({studentOpt, isDown: false})
    this.getHasCourseCalendar(studentOpt.id)
    this.getFeedbackTotal(studentOpt.id)
  },
  dateInit (setYear, setMonth) {
    let dotList = this.data.monthCourseList
    //全部时间的月份都是按0~11基准，显示月份才+1
    let dateArr = [];                       //需要遍历的日历数组数据
    let now = setYear ? new Date(setYear, setMonth) : new Date();
    let year = setYear || now.getFullYear();
    let nextYear = 0;
    let month = setMonth || now.getMonth();                 //没有+1方便后面计算当月总天数
    let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
    let startWeek = new Date(year + '/' + (month + 1) + '/' + 1).getDay();                          //目标月1号对应的星期
    let dayNums = new Date(year, nextMonth, 0).getDate();               //获取目标月有多少天
    let obj = {};
    let num = 0;
    if (month + 1 > 11) {
      nextYear = year + 1;
      dayNums = new Date(nextYear, nextMonth, 0).getDate();
    }
    let arrLen = startWeek + dayNums;
    for (let i = 0; i < arrLen; i++) {
      if (i >= startWeek) {
        num = i - startWeek + 1;
        let courseNum = 0
        let isFeedBack = false
        dotList.forEach((d) => {
          let itemDate = d.courseDate.split('-');
          if (itemDate[0] * 1 == year && itemDate[1] * 1-1 == month && itemDate[2] * 1 == num) {
            courseNum = d.num
            isFeedBack = d.isFeedBack
          }
        })
        obj = {
          isToday: '' + year + (month + 1) + num,
          dateNum: num,
          courseNum,
          isFeedBack,
          weight: 5
        }
      } else {
        obj = {};
      }
      dateArr[i] = obj;
    }
    this.setData({
      dateArr: dateArr
    })
    let nowDate = new Date();
    let nowYear = nowDate.getFullYear();
    let nowMonth = nowDate.getMonth() + 1;
    let nowWeek = nowDate.getDay();
    let getYear = setYear || nowYear;
    let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;
    if (nowYear == getYear && nowMonth == getMonth) {
      this.setData({
        isTodayWeek: true,
        todayIndex: nowWeek
      })
    } else {
      this.setData({
        isTodayWeek: false,
        todayIndex: -1
      })
    }
  },
  lookToday(e){
    let datenum = e.currentTarget.dataset.datenum
    let month = e.currentTarget.dataset.month
    let year = e.currentTarget.dataset.year
    let courseDate = year + '-' + month + '-' + datenum
    this.setData({
      isCurDate:courseDate
    })
    this.getDayCourseList( this.data.studentId,courseDate)
    this.getFeedbackTotal(this.data.studentId)
  },
  // 查看反馈
  lookHandle(e){
    let courseId = e.currentTarget.dataset.courseid
    let recordId = e.currentTarget.dataset.id
    let courseNum = e.currentTarget.dataset.num
    if(courseNum>0){
      wx.navigateTo({
        url: `/pages/feedback/index?courseId=${courseId}&recordId=${recordId}`
      })
    }
  },
  // 下拉刷新
  onPullDownRefresh(){
    this.onLoad()
  }
})
